﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    // Here goes the wrapper class for WininetHook.dll
    internal static class WininetHookWrapper
    {
        public delegate void PFN_OnRequestGet([MarshalAs(UnmanagedType.LPWStr)] string verb
            , [MarshalAs(UnmanagedType.LPWStr)] string url
            , [MarshalAs(UnmanagedType.LPWStr)] string requestHeaders
            , [MarshalAs(UnmanagedType.LPWStr)] string responseHeaders
            , [MarshalAs(UnmanagedType.LPWStr)] string requestBodyFilename
            );

        private static GCHandle s_GCHandle;

        [DllImport("WininetHook.dll", CharSet = CharSet.Unicode, EntryPoint = "SetRequestCompletionCallback" )]
        private static extern void SetRequestCompletionCallback(IntPtr pfnOnRequestGet);

        public static void SetRequestCompletionCallback(PFN_OnRequestGet pfnOnRequestGet)
        {
            if (s_GCHandle.IsAllocated)
                s_GCHandle.Free();

            // prevent the GC collect
            s_GCHandle = GCHandle.Alloc(pfnOnRequestGet);
            WininetHookWrapper.SetRequestCompletionCallback(Marshal.GetFunctionPointerForDelegate(pfnOnRequestGet));
        }
    }
}
